const express = require('express');
const router = express.Router();
const connection = require('../util/db');
const dataForm = require('../util/dataForm');
// const session = require('express-session');
// router.use(session({
//     secret: '12345',
//     // name: 'testapp',   //这里的name值得是cookie的name，默认cookie的name是：connect.sid
//     cookie: {maxAge: 80000},  //设置maxAge是80000ms，即80s后session和相应的cookie失效过期
//     resave: false,
//     saveUninitialized: true
// }))
router.get('/', (req, res) => {
    console.log(req.session)

    if (req.session.username) {
        let sql = 'select * from ' + dataForm.dataform + ' where username=' + req.session.username;
        connection.query(sql, (err, result) => {
            res.send({
                code: 1,
                msg: '已登录',
                username: result[0].username,
                nickname: result[0].nickname,
                session: req.session
            });
            res.end();
        });

    } else {
        res.send({
            code: 0,
            msg: '未登录',
            session: req.session
        });
        res.end();
    }

});

router.post('/', (req, res) => {
    // connection.connect();
    let {username, password} = req.body;
    let sql = 'select * from ' + dataForm.dataform + ' where username=' + username;
    connection.query(sql, (error, result) => {
        if (result == undefined) {
            res.send({
                code: 0,
                msg: '不存在此用户名，请注册'
            });
            res.end();
        } else {
            if (password == result[0].password) {

                req.session.username = username;
                console.log(req.session)
                res.send({
                    code: 1,
                    msg: '登陆成功',
                    username,
                    nickname:result[0].nickname,
                    session: req.session
                });
                res.end();
            } else {
                res.send({
                    code: 2,
                    msg: '密码错误'
                });
                res.end();
            }
        }
    });
    // connection.end();
});
router.get('/exit',(req,res)=>{
    req.session.username=null;
    res.send({msg:'成功退出'});
    res.end();
});
module.exports = router;